<?php

/**
 * This is the model class for table "product".
 */

require_once dirname(__FILE__) . '/base/ProductBase.php';
class Product extends ProductBase
{
    public $name;
    public $description;

    const STATUS_ACTIVE = 1, STATUS_DEACTIVE = 0;
    public $dateUpdated = array('from'=>'','to'=>'');
    
    public function getCurrencyList()
    {
        return array(
            'VNĐ' => 'VNĐ',
            'USD' => 'USD',
        );
    }

    public function getStatusOptions()
    {
        return array(
            self::STATUS_DEACTIVE => 'Inactive',
            self::STATUS_ACTIVE => 'Active',
        );
    }

    public function getStatusText()
    {
        $options = $this->getStatusOptions();
        return isset($options[$this->status]) ? $options[$this->status] : Yii::t('app', 'Unknown {att}', array('{att}' => $this->status));
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'languageProducts' => array(self::HAS_MANY, 'LanguageProduct', 'product_id'),
            'localeProduct' => array(self::HAS_ONE, 'LanguageProduct', 'product_id'),
        );
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('category_id', 'required'),
            array('category_id, status, price', 'numerical', 'integerOnly' => true),
            array('images', 'length', 'max' => 255),
            array('price', 'length', 'max' => 20),
            array('currency', 'length', 'max' => 10),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, category_id, dateUpdated, status, name', 'safe', 'on' => 'search'),
        );
    }

    public function behaviors()
    {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'create_time',
                'updateAttribute' => 'update_time',
            )
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search($selectedLocale)
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;
        $criteria->with = array(
            'localeProduct' => array(
                'condition' => 'locale=:locale',
                'params' => array(':locale' => $selectedLocale)
            ),
        );
        
        $criteria->order = 't.update_time DESC, t.id DESC';
        
        if ($this->category_id!='')
        {
            $res = FSM::run('Core.Category.getRootAndChildrenIds',array('id'=>$this->category_id,'status'=>self::STATUS_ACTIVE));
            $catIds = $res->ids;
            $criteria->addInCondition('t.category_id', $catIds);
        }

        $criteria->compare('localeProduct.name', $this->name, true);
        $criteria->compare('t.status', $this->status);
        
        // filter date_created - dateCreated
        if (is_array($this->dateUpdated) && isset($this->dateUpdated['from'], $this->dateUpdated['to']) && (empty($this->dateUpdated['from']) === false || empty($this->dateUpdated['to']) === false)) {
            $from = $this->dateUpdated['from'];
            $from = CDateTimeParser::parse($from, 'dd/MM/yyyy');
            if ($from === false) {
                $from = date('Y-m-d', strtotime('-1 years'));
            } else
                $from = date('Y-m-d', $from);
            $to = $this->dateUpdated['to'];
            $to = CDateTimeParser::parse($to, 'dd/MM/yyyy');
            if ($to === false) {
                $to = date('Y-m-d', strtotime('+1 years'));
            } else
                $to = date('Y-m-d', $to);
            
            $criteria->addCondition("DATE(t.update_time) BETWEEN DATE('".$from."') AND DATE('".$to."')");
        }

        return new CActiveDataProvider(get_class($this), array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => Settings::BO_PAGE_SIZE
            ),
        ));
    }
    
    public function getLanguageCategorySection($locale)
    {
        $langCat = LanguageCategory::model()->find('category_id=:catId AND locale=:locale',array(':catId'=>$this->category_id,':locale'=>$locale));
        if (!is_null($langCat))
            return $langCat->title;
        return '';
    }
}